package com.cyx.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.cyx.api.RemoteJudgeService;
import com.cyx.api.domain.JudgeSubmitDTO;
import com.cyx.api.domain.UserExeResult;
import com.cyx.api.domain.vo.UserQuestionResultVO;
import com.cyx.common.core.constants.Constants;
import com.cyx.common.core.domain.R;
import com.cyx.common.core.enums.ProgramType;
import com.cyx.common.core.enums.QuestionResType;
import com.cyx.common.core.enums.ResultCode;
import com.cyx.common.core.utils.ThreadLocalUtil;
import com.cyx.common.security.exception.ServiceException;
import com.cyx.friend.domain.question.Question;
import com.cyx.friend.domain.question.QuestionCase;
import com.cyx.friend.domain.question.es.QuestionES;
import com.cyx.friend.domain.user.UserSubmit;
import com.cyx.friend.domain.user.dto.UserSubmitDTO;
import com.cyx.friend.elasticsearch.QuestionRepository;
import com.cyx.friend.mapper.question.QuestionMapper;
import com.cyx.friend.mapper.user.UserSubmitMapper;
import com.cyx.friend.rabbitmq.JudgeProducer;
import com.cyx.friend.service.user.IUserQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserQuestionServiceImpl implements IUserQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private JudgeProducer judgeProducer;

    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        Integer programType = userSubmitDTO.getProgramType();
        if(ProgramType.JAVA.getValue().equals(programType)) {
            // 执行Java代码处理逻辑
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitmqSubmit(UserSubmitDTO userSubmitDTO) {
        Integer programType = userSubmitDTO.getProgramType();
        if(ProgramType.JAVA.getValue().equals(programType)) {
            // 执行Java代码处理逻辑
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);
        UserQuestionResultVO userQuestionResultVO = new UserQuestionResultVO();
        if(userSubmit == null) {
            userQuestionResultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        } else {
            userQuestionResultVO.setPass(userSubmit.getPass());
            userQuestionResultVO.setExeMessage(userSubmit.getExeMessage());
            if(StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                userQuestionResultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return userQuestionResultVO;
    }

    // 构造判题所需要的实体
    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO userSubmitDTO) {
        // 先获取题目id
        Long questionId = userSubmitDTO.getQuestionId();
        // 根据题目id从es中查询题目
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        // 判题所需参数实体
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();

        if(questionES != null) { // es中有直接copy
            BeanUtil.copyProperties(questionES, judgeSubmitDTO);
        } else { // es中没有，去数据库中查询
            Question question = questionMapper.selectById(questionId);
            // copy
            BeanUtil.copyProperties(question, judgeSubmitDTO);
            // 将题目添加到es中去
            questionES = new QuestionES();
            BeanUtil.copyProperties(question, questionES);
            questionRepository.save(questionES);
        }
        // 构造其他属性
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID, Long.class)); // 从ThreadLocal中获取userid
        judgeSubmitDTO.setExamId(userSubmitDTO.getExamId());
        judgeSubmitDTO.setProgramType(userSubmitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(splitUserCode(userSubmitDTO.getUserCode(), questionES.getMainFunc()));
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }

    private String splitUserCode(String userCode, String mainFunc) {
        String targetChar = "}";
        int targetLastIndex = userCode.lastIndexOf(targetChar);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
